import { defineStore } from 'pinia';
import apiService from '../services/api';

export const useMovieStore = defineStore('movie', {
  state: () => ({
    movies: [],
    currentMovie: null,
    totalPages: 1,
    currentPage: 1
  }),
  actions: {
    async fetchMovies(params = {}) {
      try {
        const typeIndex = 3; // movies在tableNames中的索引
        const response = await apiService.getAllItems({ 
          typeIndex, 
          page: params.page || 1,
          search: params.search || '',
          category: params.category || ''
        });
        this.movies = response.items || response;
        this.totalPages = response.totalPages || 1;
        this.currentPage = params.page || 1;
        return response;
      } catch (error) {
        console.error('Failed to fetch movies:', error);
        throw error;
      }
    },
    async getMovie(id) {
      try {
        const response = await apiService.getSingle({ id, typeIndex: 3 });
        this.currentMovie = response;
        return response;
      } catch (error) {
        console.error('Failed to fetch movie:', error);
        throw error;
      }
    },
    async addMovie(movieData) {
      try {
        const response = await apiService.addItem({...movieData, typeIndex: 3});
        this.movies.unshift(response);
        return response;
      } catch (error) {
        console.error('Failed to add movie:', error);
        throw error;
      }
    },
    async updateMovie(id, movieData) {
      try {
        const response = await apiService.updateItem({id, ...movieData, typeIndex: 3});
        const index = this.movies.findIndex(m => m.id === id);
        if (index !== -1) this.movies[index] = response;
        return response;
      } catch (error) {
        console.error('Failed to update movie:', error);
        throw error;
      }
    },
    async deleteMovie(id) {
      try {
        await apiService.deleteItem({id, typeIndex: 3});
        this.movies = this.movies.filter(m => m.id !== id);
      } catch (error) {
        console.error('Failed to delete movie:', error);
        throw error;
      }
    }
  }
});